<template>
  <base-breadcrumb>
    <div>
      <a-card :bordered="false">
        <title-name v-if="type=='view'|| type == 'approve'" title="查看设计需求申请"></title-name>
        <a-form-model ref="ruleForm" :model="form" :rules="rules"
                      :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                      :wrapperCol="{ lg: { span: 18 }, sm: { span: 18 } }"
        >
          <a-row>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="设计需求类型" prop="designDemandType"
              >
                <BaseInput v-model="form.designDemandType" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="设计需求名称" prop="designDemandName"
              >
                <BaseInput disabled v-model="form.designDemandName"
                           placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="期望回复时间"
                :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
                :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
                prop="expectRecoveryTime"
              >
                <a-date-picker
                  style="width: 100%"
                  @change="onChangeTime"
                  v-model="form.expectRecoveryTime"
                  :disabled="type == 'view' || type == 'approve'"
                  placeholder="请选择日期"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <!-- 项目部 -->
          <a-row>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="单位名称"
                                 :labelCol="{lg: {span: 6}, sm: {span:6}}"
                                 :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="branchId"
              >
                <BaseInput v-model="form.branchName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8" v-if="form.projectName">
              <a-form-model-item label="项目名称"
                                 :labelCol="{lg: {span: 6}, sm: {span:6}}"
                                 :wrapperCol="{lg: {span: 18}, sm: {span: 18} }" prop="projectId"
              >
                <BaseInput v-model="form.projectName" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8" v-if="form.projectNum">
              <a-form-model-item
                label="项目编号" prop="projectNum"
              >
                <BaseInput v-model="form.projectNum" disabled></BaseInput>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8" v-if="form.designType">
              <a-form-model-item
                label="项目设计管理类别" prop="designType"
              >
                <BaseInput v-model="form.designType" disabled></BaseInput>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="提出部门" prop="proposeDeptId"
              >
                <BaseInput v-model="form.proposeDept" disabled />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="提出人" prop="proposePersonId"
              >
                <BaseInput v-model="form.proposePersonName" disabled></BaseInput>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="创建人"
              >
                <BaseInput v-model="form.creatorName" disabled></BaseInput>
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item
                label="创建时间"
              >
                <BaseInput v-model="form.createTime" disabled></BaseInput>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="24" :sm="24">
              <a-form-model-item label="需求概述">
                <div v-html="form.information" style="height: 28px; line-height:33px;"></div>
              </a-form-model-item>
            </a-col>
          </a-row>

        </a-form-model>

        <title-name title="上传相关附件"></title-name>
        <div>
          <a-row>
            <a-col :md="24" :sm="19">
              <div class="table-operator">
                <!-- <a-upload v-if="type !='view'"  name="file" :showUploadList='false' :before-upload="beforeUpload" @change="handleChanges">
                  <a-button  disabled type="primary" style="margin-bottom: 20px;"><a-icon type="upload"  style="font-size: 1.2rem" />上传</a-button>
                </a-upload>
                <a-button v-if="type !='view'" type="" style="margin-bottom: 20px;margin-left: 20px" @click="deleteExteriorFile()"><a-icon   style="font-size: 1.2rem" />删除</a-button> -->

                <a-table bordered rowKey="id" :columns="columnAssment" :data-source="dataAssement">
                  <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span><span slot="action"
                                                                                                   slot-scope="text, record, index"
                >
                    <a :href="'/api/ycloud-file-center/oper/download?access_token='+token+'&fileId='+record.fileId"
                       target="_parent"
                    >导出</a>
                </span>
                </a-table>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-card>
      <div class="footer page-btn-right-top" v-if="!isAudit">
        <a-button disabled :loading="loadings" type="primary" @click="saveDraft()">保存草稿</a-button>
        <a-button disabled :loading="loadingSubmit" type="primary" @click="saveSubmit()">提交</a-button>
        <a-button type="default" @click="goBack">关闭</a-button>
      </div>
    </div>
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import { STable, Ellipsis } from '@/components'
import EditorBar from '@/components/Editor/editor'
import { addBasic, getProjectType } from '@/api/design/plotsPlan'
import { addScoreList, editScoreList } from '@/api/evaluate'
import { addDemandList, getDetails, editDemandList, deleteFiles } from '@/api/design/demand'
import { getTypes, getUsersDetail, getOrgUsers, getOrganizeUserList, getDept } from '@/api/commons'
import { themeChoose } from '@/mixin/mixin'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import { getProjectsDel } from '@/api/project/projects'
import { uploadFile, deleteUploadFile } from '@/api'
import { getCompany, getCurrentUserBranchCom, getAuditProject } from '@/api/themeChoose/themeChoose'

const columnAssment = [
  {
    title: '序号',
    dataIndex: 'serial',
    width: '5%',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '附件名称',
    dataIndex: 'fileName',
    width: '35%'
  },
  {
    title: '附件格式',
    dataIndex: 'suffixName',
    width: '35%'
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'a' + Date.now(),
  mixins: [themeChoose],
  props: { isAudit: { type: Boolean, default: false } },
  components: {
    STable,
    EditorBar,
    SelectSubCompany,
    SelectProject
  },
  data() {
    return {
      loading: false,
      loadings: false,
      loadingSubmit: false,
      titleName: '',
      columnAssment,
      dataAssement: [],
      uploadFile: {},
      deleteObj: {},
      token: '',
      fileFileds: null,
      fileIds: [],
      dataSource: [],
      fileArrysDataList: [],
      forms: {},

      // 查询参数
      queryParam: {},

      selectedRowKeys: '',
      selectedRows: '',

      confirmLoading: false,
      id: '',
      // 附件上传
      listUrl: '',
      deleteUrl: '',
      uploadArrys: [],
      uploadList: ' ',
      memberList: [],
      businessId: ' ',
      businessCode: 'PM24',
      reqMethod: 'post',
      name: '',
      typeList: [],
      deptList: [],
      branchLists: [],
      deptId: '',
      proposePerson: {},
      designType: [],
      test: '',
      isClear: false,
      information: '',
      editorContent: '',
      status: '',
      projectLevel: false,//是否为项目部层级
      branchLevel: false,//是否为分公司层级
      companyLevel: false,//是否为公司层级
      pageType: '',
      jobsList: [],
      currentProjectList: [],
      userId: '',
      branchName: '',
      user: '',
      type: '',
      disabled: false,
      form: {
        branchId: '',
        proposeDept: '',
        createTime: '',
        creatorName: ''
      },
      visible: false,
      companyLists: [],
      branchCompanyLists: [],
      rules: {
        designDemandTypeId: [{ required: true, message: '请选择设计需求类型', trigger: 'change' }],
        designDemandName: [{ required: true, message: '请输入设计需求名称', trigger: 'blur' }],
        branchId: [{ required: true, message: '请选择单位名称', trigger: 'change' }],
        expectRecoveryTime: [{ required: true, message: '请选择期望回复时间', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        proposeDeptId: [{ required: true, message: '请选择提出部门', trigger: 'change' }],
        proposePersonId: [{ required: true, message: '请选择提出人', trigger: 'change' }],
        information: [{ required: true, message: '请输入需求概述', trigger: 'blur' }]
      }
    }
  },
  watch: {
    isAudit: {
      handler() {
        if (this.isAudit) {
          this.type = 'view'
        }
      }
    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
          let fileFileds = []
          let fileIds = []
          selectedRows.forEach(function(obj, i) {
            fileFileds.push(obj.fileId)
            fileIds.push(obj.commonId)
          })
          this.fileFileds = fileFileds.join(',')   // 删除公共附件
          this.fileIds = fileIds                   // 有业务id 删除附件
        }
      }
    }
  },
  created() {
    this.token = Vue.getAcloudProvider().getAccessToken()
    this.userId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).id
    this.form.creatorName = JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.name
    this.id = this.$route.query.id
    this.status = this.$route.query.status
    this.type = this.$route.query.type

    this.getDetails()
    this.getUsersDetail()

  },
  methods: {
    // projectLevel:false,//是否为项目部层级
    // branchLevel:false,//是否为分公司层级
    // companyLevel:false,//是否为公司层级
    getTypes() {

      let code = ''
      if (this.projectLevel) {
        code = 'xmb'
      } else {
        code = 'gs'
      }
      getTypes({ type: '22', code: code }).then(res => {
        this.typeList = res.data
      })
    },
    onChangeTime(val) {
      this.form.expectRecoveryTime = val.format('YYYY-MM-DD')
      if (new Date(this.form.expectRecoveryTime).getTime() < new Date(this.form.createTime).getTime()) {
        this.$message.error('期望回复时间不能早于申请创建时间')
        this.$set(this.form, 'expectRecoveryTime', '')
      }
    },
    changeCompanyList(value) {

    },
    getCurrentUserBranchCom() {
      let that = this
      getCurrentUserBranchCom({ tagCodes: ['BC'] }).then(res => {
        that.branchCompanyLists = res.data
        if (that.projectLevel) {
          // this.form.branchId
          that.$set(that.form, 'branchId', that.branchCompanyLists[0].orgId)
          that.form.branchId = that.branchCompanyLists[0].orgId || that.form.branchId

          getAuditProject({ branchComIds: [that.form.branchId], auditStatus: 2 }).then(res => {
            that.currentProjectList = res.data
            that.loading = false
            that.$set(that.form, 'projectId', that.currentProjectList[0].projectId)
            that.$set(that.form, 'projectNum', that.currentProjectList[0].projectNum)
            that.$set(that.form, 'designType', that.currentProjectList[0].designTypeName)
            that.$set(that.form, 'designTypeId', that.currentProjectList[0].designTypeId)
            that.deptId = that.currentProjectList[0].projectDeptId
            getOrganizeUserList({ id: that.form.projectId }).then(res => {
              that.memberList = res.data
            })
          })
        }
      })
    },

    changeCompany(val) {
      this.$set(this.form, 'projectId', '')
      this.$set(this.form, 'projectNum', '')
      this.$set(this.form, 'designType', '')
      this.$set(this.form, 'designTypeId', '')
      this.$set(this.form, 'proposePersonId', '')
      this.$set(this.form, 'proposeDeptId', '')
      getAuditProject({ branchComIds: [val], auditStatus: 2 }).then(res => {
        this.currentProjectList = res.data
        this.loading = false
        this.$set(this.form, 'projectId', this.currentProjectList[0].projectId)
        this.$set(this.form, 'projectNum', this.currentProjectList[0].projectNum)
        this.$set(this.form, 'designType', this.currentProjectList[0].designTypeName)
        this.$set(this.form, 'designTypeId', this.currentProjectList[0].designTypeId)
      })
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },
    fileArrysData(val) {
      this.fileArrysDataList = val
    },
    // 上传

    beforeUpload(info) {
      this.uploadFile = info
      return false
    },

    handleChanges(info) {
      let that = this
      const data = new FormData()
      data.append('file', that.uploadFile)
      data.append('businessCode', that.businessCode)
      let arr = []
      uploadFile(data).then(res => {
        if (res.code === 200) {
          arr.push(res.data)
          if (that.dataAssement == null) {
            that.dataAssement = arr
          } else {
            that.dataAssement = that.dataAssement.concat(arr)
          }

          let commonIds = []
          that.dataAssement.forEach && that.dataAssement.forEach((item) => {
            commonIds.push(item.commonId)
          })

          that.form.designFileIdsInfo = that.dataAssement
          that.form.designFileIds = commonIds
        }
      })
    },
    deleteExteriorFile() {
      let that = this
      if (that.selectedRowKeys.length == 0) {
        that.$message.error('请先选中需要删除的附件！')
        return
      }
      if (that.id) {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            deleteFiles({ businessId: that.id, fileList: that.fileIds }).then(res => {
              if (res.code == 200 || res.data.code == 200) {
                that.$message.success('删除附件成功！')
                that.selectedRowKeys = []
                that.selectedRows = []
                that.getDetails()
              }
            })
          },
          onCancel() {
          }
        })

      } else {
        that.$confirm({
          title: '删除',
          content: '确定删除附件吗？',
          onOk() {
            deleteUploadFile({ fileIds: that.fileFileds }).then(res => {
              if (res.code == '0' || res.data.code == '0') {
                let data = that.dataAssement
                let selectDatas = that.fileIds
                that.dataAssement = data.filter(item => {
                  return !selectDatas.includes(item.commonId)
                })
                that.$message.success('删除附件成功！')
                that.selectedRowKeys = []
                that.selectedRows = []
              }
            })
          },
          onCancel() {
          }
        })

      }

    },

    onSelectChanges(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      let fileFileds = []
      let fileIds = []
      selectedRows.forEach(function(obj, i) {
        fileFileds.push(obj.commonId)  //
        fileIds.push(obj.fileId)
      })
      this.fileFileds = fileFileds.join(',')
      this.fileIds = fileIds

    },
    getDept() {
      if (this.deptId) {
        getDept({ id: this.deptId }).then(res => {
          this.deptList = res.data
          this.loading = false
        })
      }
    },
    changeProject(value) {
      this.$set(this.form, 'proposeDeptId', '')
      this.$set(this.form, 'proposePersonId', '')
      this.loading = true
      this.deptList = []
      this.memberList = []
      getProjectsDel({ projectId: value }).then(res => {
        this.form.designType = res.data.designName
        this.form.projectNum = res.data.projectNum
        this.form.designId = res.data.designId
        this.deptId = res.data.projectDeptOrgId
      })
      getOrganizeUserList({ id: value }).then(res => {
        this.memberList = res.data
        this.loading = false
      })
    },

    getDetails() {
      if (this.id) {
        getDetails({ id: this.id }).then(res => {
          this.form = res.data
          this.dataAssement = res.data.designFileIdsInfo
          if (!this.dataAssement) {
            this.dataAssement = []
          }
          if (this.projectLevel) {
            if (this.form.projectId){
              getOrganizeUserList({ id: this.form.projectId }).then(res => {
                this.memberList = res.data
              })
            }
          }
        })
        getDept({ id: this.form.projectDeptOrgId }).then(res => {
          this.deptList = res.data
        })
      }
    },
    getUsersDetail() {

      let that = this
      getUsersDetail({ userId: that.userId }).then(res => {
        that.branchLevel = res.data.levels.filter(item => item.code == 'BC').length >= 1 //分公司级
        that.branchLists = res.data.levels.filter(item => item.code == 'BC')
        that.companyLevel = res.data.levels.filter(item => item.code == 'CO').length >= 1 //公司级
        that.companyLists = res.data.levels.filter(item => item.code == 'CO')
        that.projectLevel = res.data.levels.filter(item => item.code == 'PD').length >= 1 //项目级

        that.getTypes()
        that.getCurrentUserBranchCom()
        if ((that.branchLevel) && !that.projectLevel) {

          let arrList = []
          that.branchLists.forEach(item => {
            arrList = res.data.posts.filter(item1 => item1.orgParentId == item.id)
          })
          let arr = []
          let arrs = []
          arrList.forEach(item => {
            arr.push(item.orgName)
            arrs.push(item.orgId)
          })
          that.form.proposeDept = arr.join(',')
          that.form.proposeDeptId = arrs.join(',')
          that.form.proposePersonName = res.data.name
          that.form.proposePersonId = res.data.id
          this.$set(this.form, 'branchName', that.branchLists[0].name)
          this.$set(this.form, 'branchId', that.branchLists[0].id)
        } else if (that.companyLevel && !that.branchLevel && !that.projectLevel) {
          this.$set(this.form, 'branchName', that.companyLists[0].name)
          this.$set(this.form, 'branchId', that.companyLists[0].id)
          that.form.proposePersonName = res.data.name
          that.form.proposePersonId = res.data.id

          let arrList = []
          that.companyLists.forEach(item => {
            arrList = res.data.posts.filter(item1 => item1.orgParentId == item.id)
          })
          let arr = []
          let arrs = []
          arrList.forEach(item => {
            arr.push(item.orgName)
            arrs.push(item.orgId)
          })
          that.form.proposeDept = arr.join(',')
          that.form.proposeDeptId = arrs.join(',')
        }
      })
    },
    selectProject(value) {
      let arr = []
      arr.push(value)
      getProjectType({ projectIds: arr }).then(res => {
        this.form.projectNum = res.data[0].projectNumber
        this.form.designType = res.data[0].designTypeName
        this.form.designTypeId = res.data[0].designTypeId
        // if(this.form.designType=="B类"){
        //   this.tableData = this.tableData1
        // }else if(this.form.designType=="C类"){
        //   this.tableData = this.tableData2
        // }

      })
    },
    saveDraft() {
      this.form.proposePersonName = this.proposePerson.label
      let arr1 = []
      let arr2 = []
      if (this.projectLevel) {
        if (this.form.branchId) {
          arr1 = this.branchCompanyLists.filter(item => item.orgId == this.form.branchId)
          if (arr1) {
            this.form.branchName = arr1[0].orgName
          }
        }

        if (this.form.proposeDeptId) {
          arr2 = this.deptList.filter(item => item.id == this.form.proposeDeptId)
          if (arr2) {
            this.form.proposeDept = arr2[0].name
          }
        }
      }

      this.$refs.ruleForm.validate((valid, value) => {
        if (valid) {
          if (this.form.designFileIdsInfo) {
            let arr = []
            this.form.designFileIdsInfo.forEach(item => {
              arr.push(item.commonId)
            })
            this.form.designFileIds = arr
          }
          this.form.statusCode = '0'
          if (this.id) {
            this.loadings = true
            editDemandList(this.form).then(res => {
              this.loadings = false
              this.$router.push('/project/design/demand')
              if (res.code == 200 || res.data.code == 200) {
                this.$message.success('保存草稿成功')
              }
            })
          } else {
            this.loadings = true
            addDemandList(this.form).then(res => {
              this.loadings = false
              if (res.code == 200 || res.data.code == 200) {
                this.$router.push('/project/design/demand')
                this.$message.success('保存草稿成功')
              }
            })
          }
        }else {
          //this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    saveSubmit() {
      // this.form.proposeDept=this.proposeDept.label
      // this.form.proposeDeptId = this.proposeDept.key
      this.form.proposePersonName = this.proposePerson.label
      let arr1 = []
      let arr2 = []
      if (this.projectLevel) {
        if (this.form.branchId) {
          arr1 = this.branchCompanyLists.filter(item => item.orgId == this.form.branchId)
          if (arr1) {
            this.form.branchName = arr1[0].orgName
          }
        }
        if (this.form.proposeDeptId) {
          arr2 = this.deptList.filter(item => item.id == this.form.proposeDeptId)
          if (arr2) {
            this.form.proposeDept = arr2[0].name
          }
        }
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.form.designFileIdsInfo) {
            let arr = []
            this.form.designFileIdsInfo.forEach(item => {
              arr.push(item.commonId)
            })
            this.form.designFileIds = arr
          }
          this.form.statusCode = '1'
          if (this.id) {
            this.loadingSubmit = true
            editDemandList(this.form).then(res => {
              this.loadingSubmit = false
              if (res.code == 200 || res.data.code == 200) {
                this.$router.push('/project/design/demand')
                this.$message.success('提交成功')
              }
            })
          } else {
            this.loadingSubmit = true
            addDemandList(this.form).then(res => {
              this.loadingSubmit = false
              if (res.code == 200 || res.data.code == 200) {
                this.$router.push('/project/design/demand')
                this.$message.success('提交成功')
              }
            })
          }
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    goBack() {
      window.close()
    },
    change(value) {
      // if(value.length>40){
      //   value = value.subString(0,40)
      // }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    search() {
      this.$refs.table.refresh(true)
    },
    goAdd() {
      this.visible = true
    },
    handleSub(record, type) {
      this.visible = true
      this.type = type
      this.form = record
    },
    handleEdit(record) {
      this.visible = true
      this.form = record
    },
    handleOk() {
      this.visible = false
      if (this.form.id) {
        editScoreList(this.form).then((res) => {
          if (res.code == '200') {
            this.$message.success('编辑成功')
          }
        })
      } else {
        addScoreList(this.form).then((res) => {
          if (res.code == '200') {
            this.$message.success('新增成功')
          }
          this.$refs.table.refresh(true)
        })
      }
    },
    handleCancel() {
      this.visible = false
    }
  }
}
</script>

<style scoped>
/deep/ .ant-form-item .ant-form-item-control-wrapper {
  width: calc(100% - 135px) !important;
}

.input {
  width: 100%
}

.footer {
  float: right;
  margin-right: 10px
}

.footer button {
  margin-left: 10px
}
</style>
